iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0
自我挑戰組

Maker making IoT !!系列 第 18

[Day17] Esp32用STA mode + Relay

  • 分享至 

  • xImage
  •  

1.前言

各位有理解loop中很長的咒語嗎?不懂得可以多看幾次,不要氣餒,文章不會跑走,所以繼續加油吧~那今天就不廢話那麼多呢,今天如標題一樣要介紹STA mode,我相信如果看過Relay AP與LED AP的程式碼,應該就不難猜到Relay STA也是相同情況,只能跟你們這群優秀得各位說,一點都猜得沒錯,但在下一篇結束後,會進入讀取數值的應用,各位可以期待一下~

2.接線圖

和STA AP接線相同

圖片取自:使用者拍攝

3.程式碼

#include <WiFi.h>
// Replace with your network credentials
const char* ssid     = "xxxx";  //AP分享器SSID
const char* password = "xxxxxxxx";    //AP分享器密碼
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output22State = "off";
String output23State = "off";

// Assign output variables to GPIO pins
const int output22 = 22;
const int output23 = 23;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output22, OUTPUT);
  pinMode(output23, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output22, LOW);
  digitalWrite(output23, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
        // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /22/on") >= 0) {
              Serial.println("GPIO 22 on");
              output22State = "on";
              digitalWrite(output22, HIGH);
            } else if (header.indexOf("GET /22/off") >= 0) {
              Serial.println("GPIO 22 off");
              output22State = "off";
              digitalWrite(output22, LOW);
            } else if (header.indexOf("GET /23/on") >= 0) {
              Serial.println("GPIO 23 on");
              output23State = "on";
              digitalWrite(output23, HIGH);
            } else if (header.indexOf("GET /23/off") >= 0) {
              Serial.println("GPIO 23 off");
              output23State = "off";
              digitalWrite(output23, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 22  
            client.println("<p>GPIO 22 - State " + output22State + "</p>");
            // If the output22State is off, it displays the ON button       
            if (output22State=="off") {
              client.println("<p><a href=\"/22/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/22/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 23  
            client.println("<p>GPIO 23 - State " + output23State + "</p>");
            // If the output23State is off, it displays the ON button       
            if (output23State=="off") {
              client.println("<p><a href=\"/23/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/23/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

這邊一樣要記住ssid跟password要填寫正確,如果填寫錯誤Esp32s將會無法連結到AP(手機基地台或AP(WiFi)分享器)

4.操作畫面

利用手機或筆電等裝置,並打開WiFi連接至AP或手機基地台,後續打開瀏覽器並輸入Esp32s的IP(這邊需要透過Arduino中的監控視窗查看)

圖片取自:使用者拍攝

圖片取自:使用者拍攝

歡迎交流

好了,不知不覺已經介紹完2個很常使用到的元件了,下一篇會講解html的基礎寫法,就不會有程式碼的介紹拉,因為都大概介紹完了,如果有不懂可以在下方留言區留言,如有看到就會幫你們解答疑問,那如開頭所講,下一篇結束後會開始進入感測器時代,並會透過那個感測器做出許多應用,那這邊就稍微賣點關東煮 (我就是想賣關東煮),所以先不講是甚麼元件,那就明天見拉


上一篇
[ Day16] Esp32s用AP mode + Relay - (程式碼講解)
下一篇
[Day18] Esp32用STA mode + Relay - (程式碼講解)
系列文
Maker making IoT !!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言